package com.bjsdzk.collector.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;

@Configuration
public class MongoConfig {

	@Autowired
	private Environment env;
	
	 @Value("${spring.data.mongodb.uri}")
     private String MONGO_URI;
	
    @Primary
    @Bean(name="mongoTemplate")
    public MongoTemplate getMongoTemplate(MongoClientOptions mongoOptions) {
    	MongoClientURI mongoClientURI = new MongoClientURI(MONGO_URI,MongoClientOptions.builder(mongoOptions));
    	return new MongoTemplate(new SimpleMongoDbFactory(mongoClientURI));
    }
    
    //@Bean(name="secondMongoTemplate")
    public MongoTemplate getMongoTemplate2() {
    	MongoClientURI mongoClientURI = new MongoClientURI(env.getProperty("spring.data.mongodb.secondary.uri"));
        return new MongoTemplate(new SimpleMongoDbFactory(mongoClientURI));
    }
    
    @Bean
    public MongoClientOptions mongoOptions() {
        return MongoClientOptions.builder().
        		maxConnectionIdleTime(6000)
        		.maxConnectionLifeTime(0)
        		.socketTimeout(1500)
        		.build();
        
    }
    
//    @Primary
//    @Bean
//    @ConditionalOnMissingBean
//    public ObjectMapper json(Jackson2ObjectMapperBuilder builder) {
//        return builder.createXmlMapper(false).build();
//    }
    
    
}
